import { getOperList } from '@/services/permissions/api';
import { changeOper, chargeByOperId, getCurrentUserDept, setApprove } from '@/services/user/login';
import sha1 from "@/utils/SHA1"; // 密码转义
import { isNull, showMsg } from '@/utils/utils';
import { CrownTwoTone, SwapOutlined } from '@ant-design/icons';
import { ModalForm, ProFormText } from '@ant-design/pro-form';
import { Button, Dropdown, Menu, message } from 'antd';
import { MenuInfo } from 'rc-menu/lib/interface';
import { MouseEvent, useEffect, useRef, useState } from 'react';
import { history, useModel } from 'umi';

const Index = () => {
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser;
  const mainUser = currentUser?.super_oper_entity || {}; // 超级超管

  // const [curKs, setCurKs] = useState(currentUser?.dept_name);
  const [ksList, setKsList] = useState<USERAPI.CurrentUser[]>([]);
  const [visible, setVisible] = useState<boolean>(false);
  const formRef = useRef<any>();

  useEffect(() => {
    getCurrentUserDept().then(res => {
      setKsList(res.record_list || []);
    }).catch(error => {
      showMsg(error?.data?.errmsg)
    })
  }, [])

  const handleMenuClick = (e: MenuInfo) => {
    // setCurKs(e.key);
    change(e.key, 'change');
  }

  // 更改业务科室、或退出切换
  const change = async (oper_id: string, flag?: string) => {
    await chargeByOperId({ oper_id }).then(res => {
      showMsg(flag === 'change' ? '已切换' : '已退出切换', 'success');
      history.push({ pathname: '/welcome' });
      setTimeout(() => window.location.reload(), 100);
    }).catch(res => {
      showMsg(res?.data?.errmsg)
    })
  }

  const checkUser = (item_user: USERAPI.CurrentUser) => {
    if (currentUser?.dept_level === '2' || item_user.dept_level === '2') {
      return item_user.sub_dept_code === currentUser?.dept_code
    }
    return item_user.dept_code === currentUser?.dept_code
  };

  const setDefault = async (e: MouseEvent, item: USERAPI.CurrentUser) => {
    e.stopPropagation();
    await setApprove({ oper_id: item.oper_id }).then(res => {
      showMsg(`已将【${item.dept_name}】设置为默认科室`, 'success');
      history.push({ pathname: '/welcome' });
      setTimeout(() => window.location.reload(), 100);
    }).catch((error) => {
      showMsg(error?.data?.errmsg);
    });
  };

  const getDeptShowName = (userInfo?: USERAPI.CurrentUser): string => {
    if (!userInfo && currentUser?.dept_level === '2') {
      if (currentUser?.staff_code) {
        return getDeptShowName(ksList.find(elem => elem.oper_id === currentUser.oper_id) || {});
      } else {
        return currentUser?.dept_name ?? '';
      }
    }
    userInfo = userInfo || currentUser;
    return (userInfo?.dept_name || '') + (userInfo?.dept_level === '2' ? (' > ' + userInfo?.sub_dept_name || '') : '')
  };

  return (
    <div style={{ display: 'flex', alignItems: 'center' }}>
      <div style={{ marginRight: 10, fontSize: 12 }}>{currentUser?.oper_name}</div>
      {
        mainUser?.identity_type === 'A' &&
        <Dropdown.Button
          icon={<SwapOutlined style={{ fontSize: 12 }} />}
          overlay={(
            <Menu>
              <Menu.Item>
                <a target="_blank" rel="noopener noreferrer" style={{ fontSize: 12 }}>
                  <CrownTwoTone /> 当前位置：{currentUser?.staff_code}-{currentUser?.oper_name}
                </a>
              </Menu.Item>
              <Menu.Item>
                <a target="_blank" rel="noopener noreferrer" onClick={() => setVisible(true)} style={{ fontSize: 12 }}>
                  切换账号
                </a>
              </Menu.Item>
              {
                currentUser?.staff_code !== mainUser.staff_code &&
                <Menu.Item>
                  <a target="_blank" rel="noopener noreferrer" onClick={() => { if (mainUser.oper_id) change(mainUser.oper_id) }} style={{ fontSize: 12 }}>
                    退出切换
                  </a>
                </Menu.Item>
              }
            </Menu>
          )}
          style={{ marginRight: 10 }}
          buttonsRender={([, btn2]) => [
            <Button
              icon={<img src={require('../../assets/images/door.png')} width={22} height={22} />}
              style={{ display: 'flex', alignItems: 'center' }}>
              任意门
            </Button>,
            btn2
          ]}
        />
      }
      {
        ksList.length === 1 ?
          <div style={{ padding: '2px 8px', border: '1px #ddd solid', fontSize: 12 }}>
            {getDeptShowName()}
          </div>
          :
          <Dropdown.Button
            icon={<SwapOutlined style={{ fontSize: 12 }} />}
            overlay={(
              <Menu onClick={handleMenuClick}>
                {
                  ksList.map((item, idx) => (
                    <Menu.Item key={item.oper_id || idx}>
                      <div style={{ display: 'flex', alignItems: 'center' }} className={checkUser(item) ? 'curKs' : ''}>
                        <div style={{ fontSize: 12, flex: 1 }}>{getDeptShowName(item)}</div>
                        {
                          item.is_approve === 'Y' ?
                            <span style={{ color: '#989898', fontSize: 12, marginLeft: 10, }}>默认科室</span>
                            :
                            <div style={{ textAlign: 'right', marginLeft: 10, fontSize: 12, color: '#096dd9' }} onClick={async e => await setDefault(e, item)}>设为默认</div>
                        }
                      </div>
                    </Menu.Item>
                  ))
                }
              </Menu>
            )}
          >
            <span style={{ fontSize: 12 }}>{getDeptShowName()}</span>
          </Dropdown.Button>
      }
      {visible && (
        <ModalForm
          title="切换账号"
          // trigger={<Button type="primary">自定义文字</Button>}
          formRef={formRef}
          visible
          width={400}
          layout="horizontal"
          submitter={{
            searchConfig: {
              submitText: '确认',
              resetText: '取消',
            },
          }}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          modalProps={{
            onCancel: () => setVisible(false),
            maskClosable: false,
          }}
          onFinish={async (values) => {
            // await waitTime(2000);
            await changeOper({ ...values, pwd: sha1.hex_sha1(values.pwd) })
              .then((res) => {
                message.success('正在切换...');
                history.push({ pathname: '/welcome' });
                setTimeout(() => window.location.reload(), 100);
              })

              .catch((error) => {
                showMsg(error?.data?.errmsg)
              });
          }}
        >
          <ProFormText
            width="md"
            name="dest_staff_code"
            label="工号"
            placeholder="请输入工号"
            initialValue={currentUser?.staff_code}
            rules={[
              {
                required: true,
              },
            ]}
            fieldProps={{
              onBlur: async (e) => {
                if (isNull(e.target.value)) {
                  return;
                }
                await getOperList({ staff_code: e.target.value }).then(res => {
                  if (isNull(res.record_list)) {
                    showMsg('未查到相关信息，请重新输入');
                    formRef?.current?.setFieldsValue({ dest_staff_code: null });
                    return;
                  }
                  const result = res.record_list[0];
                  // setCurOper(result);
                  formRef?.current?.setFieldsValue({ oper_name: result.staff_name, dept_name: result.admin_dept_name })
                }).catch((error) => {
                  showMsg(error?.data?.errmsg)
                })
              }
            }}
          />
          <ProFormText
            width="md"
            label="姓名"
            name="oper_name"
            readonly
            initialValue={currentUser?.oper_name}
          />
          <ProFormText
            width="md"
            label="归属科室"
            name="dept_name"
            readonly
            initialValue={currentUser?.dept_name}
          />
          <ProFormText.Password
            width="md"
            name="pwd"
            label="超管密码"
            placeholder="请输入超管密码"
            fieldProps={{
              autoComplete: 'new-password',
            }}
            rules={[
              {
                required: true,
              },
            ]}
          />
        </ModalForm>
      )}
    </div>
  );
};

export default Index;
